using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Core;
using System.IO;

namespace SPHelpCollectionBuilder
{
    public partial class HelpImageEditor : UserControl, ISavableControl
    {
        private bool _hasChanges = false;
        private HelpImage _helpImage = null;

        public HelpImage CurrentHelpImage
        {
            get { return _helpImage; }
            set { _helpImage = value; }
        }

        public HelpImageEditor()
        {
            InitializeComponent();
            this.Leave += new EventHandler(CheckUnsavedData);
        }

        public void LoadHelpImage()
        {
            if (CurrentHelpImage != null)
            {
                textBoxName.Text = CurrentHelpImage.name;
                textBoxId.Text = CurrentHelpImage.id;
                textBoxCreatedDate.Text = CurrentHelpImage.createdDate;
                textBoxChangedDate.Text = CurrentHelpImage.changedDate;
                textBoxAuthor.Text = CurrentHelpImage.author;
                LoadVersions();
                comboBoxFileExtension.Text = CurrentHelpImage.contentFileExtension;
                if (CurrentHelpImage.ContentFile != null)
                {
                    textBoxImageFilePath.Text = CurrentHelpImage.ContentFile.FullName;
                    textBoxImageFilePath.ReadOnly = true;
                    btnFileOpen.Visible = false;
                }
            }
        }

        public bool HasUnsavedData
        {
            get
            {
                bool result = false;

                if (_hasChanges) return _hasChanges;

                if (string.Compare(textBoxName.Text, CurrentHelpImage.name, false) != 0)
                    result = true;

                if (string.Compare(textBoxAuthor.Text, CurrentHelpImage.author, false) != 0)
                    result = true;

                if (string.Compare(ReadVersionString(), CurrentHelpImage.version, false) != 0)
                    result = true;

                if (string.Compare(comboBoxFileExtension.Text, CurrentHelpImage.contentFileExtension, false) != 0)
                    result = true;

                if (CurrentHelpImage.ContentFile != null && string.Compare(textBoxImageFilePath.Text, CurrentHelpImage.ContentFile.FullName, false) != 0)
                    result = true;

                return result;
            }
        }

        public void SaveData()
        {
            if (HasUnsavedData)
            {
                if (string.IsNullOrEmpty(textBoxId.Text))
                {
                    MessageBox.Show("Help Item must have Id, cannot save", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                //Check there is a content file
                if (string.IsNullOrEmpty(textBoxImageFilePath.Text))
                {
                    DialogResult dResult = MessageBox.Show("No image file is chosen, save this help item without the the actual file?", "warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (dResult == DialogResult.No)
                    {
                        return;
                    }
                }

                FileInfo fi = null;
                if (!string.IsNullOrEmpty(textBoxImageFilePath.Text))
                    fi = new FileInfo(textBoxImageFilePath.Text);

                if (fi != null)
                {
                    //Check the file extension match
                    string extension = fi.Extension;
                    extension = extension.Replace(".", string.Empty);

                    if (string.Compare(extension, comboBoxFileExtension.Text, true) != 0)
                    {
                        DialogResult dResult = MessageBox.Show(string.Concat("File extension chosen is: ", comboBoxFileExtension.Text, " but the uploaded file extension is:  ", fi.Extension, " Continue?"), "warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (dResult == DialogResult.No)
                        {
                            return;
                        }
                    }
                }

                CurrentHelpImage.name = textBoxName.Text;
                CurrentHelpImage.changedDate = DateTime.Now.ToString(Utils.DEFAULT_DATETIME_FORMAT_STRNG);
                CurrentHelpImage.author = textBoxAuthor.Text;
                CurrentHelpImage.version = ReadVersionString();
                CurrentHelpImage.contentFileExtension = comboBoxFileExtension.Text;
                CurrentHelpImage.ContentFile = fi;

                //manifest entry
                CurrentHelpImage.ManifestEntry.id = CurrentHelpImage.id;

                HelpImage tmp = HCProjectManager.CurrentProject.HelpImage.Find(delegate(HelpImage img) { return string.Compare(img.id, CurrentHelpImage.id, true) == 0; });
                if (tmp == null)
                    HCProjectManager.CurrentProject.HelpImage.Add(CurrentHelpImage);
                else
                    tmp = CurrentHelpImage;
                Global.HAS_CHANGES_IN_MEMORY_NOT_SAVED_TO_DISK = true;
            }
        }

        private void btnParentHelpItem_Click(object sender, EventArgs e)
        {
            using (ParentHelpItemChooser chooser = new ParentHelpItemChooser())
            {
                chooser.LoadData(CurrentHelpImage.ManifestEntry);
                DialogResult dResult = chooser.ShowDialog(this);
                if (dResult == DialogResult.OK)
                {
                    CurrentHelpImage.ManifestEntry.Parents = chooser.ParentEntries;
                    _hasChanges = chooser.HasChanges;
                }
            }
        }

        public void CheckUnsavedData(object sender, EventArgs e)
        {
            if (this.HasUnsavedData)
            {
                this.SaveData();
                Global.HAS_CHANGES_IN_MEMORY_NOT_SAVED_TO_DISK = true;
            }
        }

        private void btnFileOpen_Click(object sender, EventArgs e)
        {
            //Check whether a content file exists
            if (!string.IsNullOrEmpty(CurrentHelpImage.ContentFileFullName) && File.Exists(CurrentHelpImage.ContentFileFullName))
            {
                DialogResult dResult = MessageBox.Show("A content file already exists for this help item, if you choose  a different file and save it, this file will be overwritten, continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dResult != DialogResult.Yes)
                    return;
            }

            DialogResult dResult1 = openFileDialog1.ShowDialog(this);
            if (dResult1 == DialogResult.OK)
            {
                textBoxImageFilePath.Text = openFileDialog1.FileName;
            }
        }

        private void buttonRelatedItem_Click(object sender, EventArgs e)
        {
            using (RelatedItemChooser chooser = new RelatedItemChooser())
            {
                chooser.LoadData(CurrentHelpImage.ManifestEntry);
                DialogResult dResult = chooser.ShowDialog(this);
                if (dResult == DialogResult.OK)
                {
                    CurrentHelpImage.ManifestEntry.relatedItemsPoitingToMe = chooser.RelatedItems;
                    _hasChanges = chooser.HasChanges;
                }
            }
        }

        private void DigitOnly(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
            {
                MessageBox.Show("Digit only", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Handled = true;
            }
        }

        private void LoadVersions()
        {
            if (string.IsNullOrEmpty(CurrentHelpImage.version))
                CurrentHelpImage.version = HCProjectManager.CurrentProject.ProjectManifest.version;

            string verionsString = CurrentHelpImage.version;
            string[] strs = System.Text.RegularExpressions.Regex.Split(verionsString, "\\.");
            if (strs.Length != 4)
                throw new Exception(string.Concat("Version number must have four parts, error version string: ", verionsString));
            textBoxVersion1.Text = strs[0];
            textBoxVersion2.Text = strs[1];
            textBoxVersion3.Text = strs[2];
            textBoxVersion4.Text = strs[3];
        }

        private string ReadVersionString()
        {
            return string.Concat(textBoxVersion1.Text, ".", textBoxVersion2.Text, ".", textBoxVersion3.Text, ".", textBoxVersion4.Text);
        }
    }
}
